﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ESOL.Common.Entity;
using ESOL.Business.Mst;
using ESOL.Business.Inv;
using ESOL.WinUI.Pur;
using ESOL.WinUI.Hr;
using ESOL.Common;

namespace ESOL.WinUI.Inv
{
    public partial class frmManageImportOrder : BaseForm.frmBaseMdiBusinessForm
    {

        #region Variable
        private InvImportOrderEntity mSelectedImportOrder;
        #endregion

        #region Constructor
        public frmManageImportOrder()
        {
            InitializeComponent();
        }
        #endregion
        
        #region Function
        private void BindComboBox()
        {
            List<MstWarehouseEntity> list = MstWarehouseBs.GetMstWarehouseAllList();
            MstWarehouseEntity entity = new MstWarehouseEntity();

            list.Insert(0, entity);
            cmbWareHouseCode.DataSource = list;
            cmbWareHouseCode.DisplayMember = "WarehouseName";
            cmbWareHouseCode.ValueMember = "WarehouseCode";

            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbOrderType, "IMT", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "IMO", true);

            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(repositoryItemGridLookUpEdit1, "IMT", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(repositoryItemGridLookUpEdit2, "IMO", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(repositoryItemGridLookUpEdit3, "UNIT", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(repositoryItemGridLookUpEdit4, "UNIT", true);

            //cmbOrderType.SelectedValue = "IMT01";
            cmbStatus.SelectedValue = "IMO01";
        }
        private string GetCondition()
        {
            string condition = "";

            if (string.IsNullOrEmpty(txtOrderCode.Text) == false)
            {
                condition += " AND A.ORDER_CODE LIKE '%" + txtOrderCode.Text + "%'";
            }
            if (string.IsNullOrEmpty(txtRelatedOrder.Text) == false)
            {
                //condition += " AND A.RELATED_ORDER LIKE '%" + txtRelatedOrder.Text + "%'";
            }
            if (dtpOrderDate.EditValue!=null)
            {
                condition += " AND A.ORDER_DATE >= CONVERT(DATETIME,'" + dtpOrderDate.EditValue + "')";
            }
            if (dtpOrderDateTo.EditValue!=null)
            {
                condition += " AND A.ORDER_DATE <= CONVERT(DATETIME,'" + dtpOrderDateTo.EditValue + "')";
            }
            if (txtOrderPerson.Tag != null && txtOrderPerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                MstPersonEntity entity = (MstPersonEntity)txtOrderPerson.Tag;
                condition += " AND A.CREATED_BY = '" + entity.PersonId + "' ";
            }

            if (txtSuppers.Tag != null && txtSuppers.Tag.GetType() == typeof(MstSupplierEntity))
            {
                MstSupplierEntity entity = (MstSupplierEntity)txtSuppers.Tag;
                condition += " AND A.RELATED_ORDER IN (SELECT ORDER_ID FROM QC_IQC_ORDER G ";
                condition += " LEFT JOIN dbo.PUR_PURCHASE_ARRIVED H ON G.PUR_ARRIVED_ID=H.ARRIVED_ID";
                condition += " LEFT JOIN dbo.PUR_PURCHASE_ARRIVED_ITEM I ON H.ARRIVED_ID=I.ARRIVED_ID";
                condition += " LEFT JOIN dbo.PUR_PURCHASE_ORDER_ITEM J ON I.PURCHASE_ITEM_ID=J.PURCHASE_ITEM_ID";
                condition += " LEFT JOIN dbo.PUR_PURCHASE_ORDER K ON J.PURCHASE_ORDER_ID=K.PURCHASE_ORDER_ID";
                condition += " LEFT JOIN dbo.MST_SUPPLIER L ON L.SUPPLIER_ID=K.SUPPLIER_ID";
                condition += " WHERE L.SUPPLIER_ID='" + entity.SupplierId + "')";
            }
            if (txtPurchaseCode.Tag != null && txtPurchaseCode.Tag.GetType() == typeof(PurPurchaseOrderEntity))
            {
                PurPurchaseOrderEntity entity = (PurPurchaseOrderEntity)txtPurchaseCode.Tag;
                condition += " AND A.RELATED_ORDER IN (SELECT ORDER_ID FROM QC_IQC_ORDER G ";
                condition += " LEFT JOIN dbo.PUR_PURCHASE_ARRIVED H ON G.PUR_ARRIVED_ID=H.ARRIVED_ID";
                condition += " LEFT JOIN dbo.PUR_PURCHASE_ARRIVED_ITEM I ON H.ARRIVED_ID=I.ARRIVED_ID";
                condition += " LEFT JOIN dbo.PUR_PURCHASE_ORDER_ITEM J ON I.PURCHASE_ITEM_ID=J.PURCHASE_ITEM_ID";
                condition += " LEFT JOIN dbo.PUR_PURCHASE_ORDER K ON J.PURCHASE_ORDER_ID=K.PURCHASE_ORDER_ID";
                condition += " WHERE K.PURCHASE_ORDER_ID='" + entity.PurchaseOrderId + "')";
            }
            if (txtPurchaseArrivedCode.Tag != null && txtPurchaseArrivedCode.Tag.GetType() == typeof(PurPurchaseArrivedEntity))
            {
                PurPurchaseArrivedEntity entity = (PurPurchaseArrivedEntity)txtPurchaseArrivedCode.Tag;
                condition += " AND A.RELATED_ORDER IN (SELECT ORDER_ID FROM QC_IQC_ORDER G ";
                condition += " LEFT JOIN dbo.PUR_PURCHASE_ARRIVED H ON G.PUR_ARRIVED_ID=H.ARRIVED_ID";
                condition += " WHERE H.ARRIVED_ID='" + entity.ArrivedId + "')";
            }

            if (string.IsNullOrEmpty(cmbWareHouseCode.Text) == false && cmbWareHouseCode.SelectedValue != null)
            {
                //condition += " AND B.WAREHOUSE_CODE = '" + cmbWareHouseCode.SelectedValue.ToString() + "'";
            }
            if (string.IsNullOrEmpty(cmbStatus.Text) == false && cmbStatus.SelectedValue != null)
            {
                condition += " AND A.STATUS = '" + cmbStatus.SelectedValue.ToString() + "'";
            }
            if (string.IsNullOrEmpty(cmbOrderType.Text) == false && cmbOrderType.SelectedValue != null)
            {
                condition += " AND A.ORDER_TYPE = '" + cmbOrderType.SelectedValue.ToString() + "'";
            }
            return condition;
        }
        private void BindDataGrid()
        {
            string condition = GetCondition();
            string rowCount = txtRowCount.Text;
            string orderBy = "A.CREATED_DATE DESC";
            DataTable dt = InvImportOrderBs.GetByCondition(condition, orderBy, rowCount);
            gvMain.DataSource = dt;
        }
        private void BindDetailGrid()
        {
            if (mSelectedImportOrder == null)
            {
                gvDetail.DataSource = null;
                return;
            }
            string ImpOrderId = mSelectedImportOrder.ImportOrderId;
            string Imptype = mSelectedImportOrder.OrderType;
            if (string.IsNullOrEmpty(ImpOrderId)||string.IsNullOrEmpty(Imptype))
            {
                gvDetail.DataSource = null;
                return;
            }
            DataSet ds = InvImportItemBs.GetDataSetByImportID(ImpOrderId, mSelectedImportOrder.OrderType);
            if (ds == null || ds.Tables.Count == 0)
            {
                gvDetail.DataSource = null;
                return;
            }
            gvDetail.DataSource = ds.Tables[0];

            for (int i = 0; i < gridView2.RowCount; i++)
            {
                if (!string.IsNullOrEmpty(ds.Tables[0].Rows[i]["LOCATION_ID_P"].ToString()))
                    {
                        DataTable dt_location = MstLocationBs.GetWarehouseLocationByLocationId(ds.Tables[0].Rows[i]["LOCATION_ID_P"].ToString());
                        if (dt_location != null && dt_location.Rows.Count > 0)
                        {
                            ds.Tables[0].Rows[i]["WAREHOUSE_CODE"] = dt_location.Rows[0]["WAREHOUSE_CODE"].ToString();
                            ds.Tables[0].Rows[i]["WAREHOUSE_NAME"] = dt_location.Rows[0]["WAREHOUSE_NAME"].ToString();
                            ds.Tables[0].Rows[i]["LOCATION_CODE"] = dt_location.Rows[0]["LOCATION_CODE"].ToString();
                        }
                    }
            }
        }
        private void ResetButtonsEnable()
        {
            btnNew.Enabled = false;
            btnModify.Enabled = false;
            btnDelete.Enabled = false;
            btnSubmit.Enabled = false;
            btnApprove.Enabled = false;
            if (mSelectedImportOrder == null)
            {
                return;
            }
            if (mSelectedImportOrder.Status == "IMO01")//待审核
            {
                btnModify.Enabled = true;
                btnDelete.Enabled = true;
                btnApprove.Enabled = true;
            }
            if (mSelectedImportOrder.Status == "IMO02")//已审核
            {
                btnModify.Enabled = false;
                btnDelete.Enabled = false;
                btnApprove.Enabled = false;
            }
            if (mSelectedImportOrder.Status == "IMO03")//已入库
            {
                btnModify.Enabled = false;
                btnDelete.Enabled = false;
                btnApprove.Enabled = false;
            }
            if (mSelectedImportOrder.Status == "IMO04")//已拒绝
            {
                btnModify.Enabled = true;
                btnDelete.Enabled = true;
                btnApprove.Enabled = true;
            }
            if (mSelectedImportOrder.Status == "IMO05")//已删除
            {
                btnModify.Enabled = false;
                btnDelete.Enabled = false;
                btnApprove.Enabled = false;
            }
        }
        #endregion

        #region Events
        private void frmImportOrderManage_Load(object sender, EventArgs e)
        {
            BindComboBox();
            BindDataGrid();
            ResetButtonsEnable();
        }
        protected override void Click_Query()
        {
            BindDataGrid();
        }
        DataRow drSelected;
        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            drSelected = gridView1.GetDataRow(e.RowHandle);
            mSelectedImportOrder = new InvImportOrderEntity(drSelected);

            BindDetailGrid();
            ResetButtonsEnable();
        }

        private void txtSuppers_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainSupplierQuery frm = new frmMaintainSupplierQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedSupplier != null)
            {
                txtSuppers.Text = frm.SelectedSupplier.SupplierName;
                txtSuppers.Tag = frm.SelectedSupplier;
            }
            else
            {
                txtSuppers.Text = "";
                txtSuppers.Tag = null;
            }
        }

        private void txtPurchaseCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainPurchaseOrderQuery frm = new frmMaintainPurchaseOrderQuery(false);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPurchaseOrder != null)
            {
                txtPurchaseCode.Text = frm.SelectedPurchaseOrder.PurchaseOrderCode;
                txtPurchaseCode.Tag = frm.SelectedPurchaseOrder;
            }
            else
            {
                txtPurchaseCode.Text = "";
                txtPurchaseCode.Tag = null;
            }
        }

        private void txtPurchaseArrivedCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

        }

        private void txtOrderPerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtOrderPerson.Text = frm.SelectedPerson.NameCn;
                txtOrderPerson.Tag = frm.SelectedPerson;
            }
            else
            {
                txtOrderPerson.Text = "";
                txtOrderPerson.Tag = null;
            }
        }

        protected override void Click_View()
        {
            if (mSelectedImportOrder == null)
            {
                MessageBox.Show("请选择一个入库申请单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            frmMaintainImportOrder frm = new frmMaintainImportOrder();
            frm.ThisActionType = ActionType.View;
            frm.SelectedImportOrder = mSelectedImportOrder;
            frm.ShowDialog();
        }
        protected override void Click_New()
        {
            base.Click_New();
        }
        protected override void Click_Modify()
        {
            if (mSelectedImportOrder == null)
            {
                MessageBox.Show("请选择一个入库申请单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            frmMaintainImportOrder frm = new frmMaintainImportOrder();
            frm.ThisActionType = ActionType.Modify;
            frm.SelectedImportOrder = mSelectedImportOrder;
            DialogResult dr = frm.ShowDialog();
            if (dr == DialogResult.OK)
            {
                BindDataGrid();
            }
        }
        protected override void Click_Delete()
        {
            if (mSelectedImportOrder == null)
            {
                MessageBox.Show("请选择一个入库申请单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DialogResult dr = MessageBox.Show("是否删除选中发货申请单？", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.No)
            {
                return;
            }
            try
            {

                mSelectedImportOrder.Status = "IMO05";
                mSelectedImportOrder.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
                mSelectedImportOrder.LastModifiedDate = DateTime.Now;
                bool successful = InvImportOrderBs.UpdateInvImportOrder(mSelectedImportOrder);//SalesDeliveryOrderBs.UpdateSalesDeliveryOrder(mSelectedDeliveryOrder);
                if (successful)
                {
                    MessageBox.Show("删除成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    BindDataGrid();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        protected override void Click_Approve()
        {
            if (mSelectedImportOrder == null)
            {
                MessageBox.Show("请选择一个入库申请单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            frmMaintainImportOrder frm = new frmMaintainImportOrder();
            frm.ThisActionType = ActionType.Approve;
            frm.SelectedImportOrder = mSelectedImportOrder;
            DialogResult dr = frm.ShowDialog();
            if (dr == DialogResult.OK)
            {
                BindDataGrid();
            }
        }
        protected override void Click_Print()
        {
            if (drSelected == null)
            {
                MessageBox.Show("请选择一张入库单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DataTable dt = gvDetail.DataSource as DataTable;
            frmPrintFormInvImportOrder frm = new frmPrintFormInvImportOrder(drSelected, dt);
            frm.Show();
        }
        #endregion

    }
}